define(
   [
      'dojo/_base/declare',
      'dojo/json'
   ],
   function (declare, JSON) {
      return declare([],
      {
         mResultsAttr:"oslc:results",
         constructor:function (args) {
            // Call Super
            dojo.safeMixin(this, args);
         },
         postscript:function (args) {
            this.inherited(arguments);

            this.mResultsSent = false;
         },
         sendCancel: function()
         {
            this.sendResults([]);
         },
         sendResult:function (pItem) {
            this.sendResults([pItem]);
         },
         sendResults:function (items) {
            if (this.mResultsSent)
               return null;

            for (pItem in items)
               pItem = this.cleanObjectOfProto(pItem);

            var oslcResponse = {};
            oslcResponse[this.mResultsAttr] = items;

            var protocol;
            if (window.location)
               protocol = window.location.hash;
            else if(document.location)
               protocol = window.location.hash;
            if (protocol == '#oslc-core-windowName-1.0')
               this.respondWithWindowName(oslcResponse);
            else if (protocol == '#oslc-core-postMessage-1.0')
               this.respondWithPostMessage(oslcResponse);
            else
               return false;

            this.mResultsSent = true;
            return true;
         },
         respondWithWindowName:function (response) {
            var returnURL = window.name;

            window.name = "oslc-response:" + JSON.stringify(response);
            window.location = returnURL;
         },
         respondWithPostMessage:function (response) {
            var str = JSON.stringify(response);
            var windowToEnvoke = window;
            if (window.parent)
               windowToEnvoke = window.parent;
            windowToEnvoke.postMessage("oslc-response:" + str, "*");
         },
         cleanObjectOfProto:function (obj) {
            var newObj = {};
            for (variable in obj) {
               if (variable[0] == '_' || variable == 'children' || variable == 'parent')
                  continue;
               newObj[variable] = obj[variable];
            }
            return newObj;
         }
      });
   }
);

